﻿using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ExtensionMethodExtravaganza
{
	public class ListViewComparer : IComparer<ListViewItem>, IComparer
	{
		private readonly ListViewItemComparer	_comparer;
		private readonly ListView				_listView;
		private int								_multiplier;

		public ListViewComparer(ListView listView, ListViewItemComparer comparer)
		{
			_listView = listView;
			_listView.ColumnClick += WhenColumnClicked;	
			_comparer = comparer;

			SetMultiplier();
		}

		private void SetMultiplier()
		{
			_multiplier = _listView.Sorting == SortOrder.Ascending ? 1 : -1;
		}

		private void WhenColumnClicked(object sender, ColumnClickEventArgs e)
		{
			if (e.Column == _comparer.ColumnIndex)
			{
				_listView.Sorting = _listView.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
			}
			else
			{
				_comparer.ColumnIndex = e.Column;
				_listView.Sorting = SortOrder.Ascending;
			}

			SetMultiplier();

			_listView.Sort();
		}

		public int Compare(ListViewItem x, ListViewItem y)
		{
			return _comparer.Compare(x, y) * _multiplier;
		}

		public int Compare(object x, object y)
		{
			return Compare((ListViewItem)x, (ListViewItem)y);
		}
	}
}